package fr.norsys.mapper.jndi;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import junit.framework.TestCase;
import fr.norsys.mapper.core.MapperException;
import fr.norsys.mapper.manager.MapperManager;
import fr.norsys.mapper.xml.XMLConfigurator;
import fr.norsys.mockldap.TestDirContextFactory;

/**
 * This class tests the cleanup process of the manager. This class configures a
 * manager with one source and one mapper and creates lot of instances of the
 * mapper without releasing them. It then checks that memory is properly cleaned
 * up.
 * 
 * @author nono
 * 
 */
public class JNDISourceCleanTest extends TestCase {

	private MapperManager mgr;

	protected void setUp() throws Exception {
		super.setUp();
		XMLConfigurator xc = new XMLConfigurator();
		this.mgr = new MapperManager();
		// parse XML configuration file
		xc.parse(Thread.currentThread().getContextClassLoader()
				.getResourceAsStream("jndi-sample.xml"));
		// configure manager
		xc.configure(this.mgr);
		this.mgr.set("ldifsource", "canam-personnes-sample.ldif");
		this.mgr.setConfigured();
		this.mgr.start();
	}

	public void test01Cleanup() throws MapperException, IOException {
		long[] data = new long[100];
		for (int i = 0; i < 1000000; i++) {
			// execute query
			SearchMapper sm = (SearchMapper) this.mgr.getMapper("telAndMail");
			/* populate input */
			Map input = new HashMap();
			input.put("nom", "FOURCADE");
			input.put("prenom", "Sandrine");
			List ret = sm.search(input, null);
			assertEquals(1,ret.size());
			if (i % 10000 == 0) {
				System.gc();
				data[i % 10000] = Runtime.getRuntime().totalMemory();
			}
		}
		System.err.println("Context count :" +TestDirContextFactory.getCount());
		/* print data to file */
		File f = new File("jndi-cleaner.data");
		PrintWriter pw = new PrintWriter(new FileWriter(f));
		int l = data.length;
		for (int i = 0; i < 100; i++)
			pw.println(data[i]);
		pw.flush();
		pw.close();
	}

	protected void tearDown() throws Exception {
		super.tearDown();
		this.mgr.stop();
	}

}
